/*
 * 自定义事件模块
 * @author li.xiaomei
 * @date 2016-09-29
 */
var SuperClass = require('./class');
var _indexOf = [].indexOf;
var Event = SuperClass.extend({
  on: function(key, listener) {
    if (!this._lists) {
      this._lists = {};
    }

    if (!this._lists[key]) {
      this._lists[key] = [];
    }

    //每个回调只监听一次
    if (_indexOf(this._lists, listener) === -1 && typeof listener ===
      'function') {
      this._lists[key].push(listener);
    }

    return this;
  },

  fire: function(key) {
    if (!this._lists || !this._lists[key]) return;

    var args = Array.prototype.slice.call(arguments, 1) || [];
    var listeners = this._lists[key];
    var i = 0,
      l = listeners.length;

    for (; i < l; i++) {
      listeners[i].apply(this, args);
    }

    return this;
  },

  off: function(key, listener) {
    if (!key && !listener) {
      this._lists = {};
    }

    if (key && !listener) {
      delete this._lists[key];
    }

    if (key && listener) {
      var listeners = this._lists[key];
      var index = _indexOf(listeners, listener);
      (index > -1 && listeners.splice(index, 1));
    }

    return this;
  }
});

module.exports = Event;
